/*

*/

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include "scanner.h"

#define INPUT_LINE_MAX 1024


/*********************************************************************************
**********                 词法分析                                  *************
***********************************************************************************/

void run(char* source) {
    initScanner(source);
    int line = -1;
    while (1) {
        Token token_once = scanToken();
        if (line != token_once.line) {
            printf("%-4d", token_once.line);
            line = token_once.line;
        }
        else {
            printf("|   ");
        }
        printf("%-4d", token_once.type);
        int len = token_once.length;
        printf("\'");
        for (int i = 0; i < len; i++) {
            printf("%c", token_once.start[i]);
        }
        printf("\'\n");
        if (token_once.type == TOKEN_EOF) {
            return;
        }
    }
}

/*********************************************************************************
**********                 从用户输出stdin读取source                 *************
***********************************************************************************/

void user_stdin_input() {
    char* source = calloc(INPUT_LINE_MAX, sizeof(char));
    if (source == NULL) {
        printf("calloc failed in char* user_stdin_input()\n");
        return;
    }
    while (1) {
        printf("请输入需要分析的源代码：\n");
        if (fgets(source, INPUT_LINE_MAX, stdin) == NULL) {
            printf("\n");
            break;
        }
        printf("\n");
        run(source);
    }
    free(source);
}


/*********************************************************************************
**********                 从用户文件读取source                      *************
***********************************************************************************/

void user_file_input(const char* user_file) {
    FILE* fp = fopen(user_file, "rb");
    if (fp == NULL) {
        perror("user_file in char* user_file_input");
        return;
    }
    fseek(fp, 0, SEEK_END);
    long file_size = ftell(fp);
    rewind(fp);
    char *source = calloc(file_size + 1, sizeof(char));
    if (source == NULL) {
        perror("source calloc in char* user_file_input");
       // printf("calloc failed in char* user_file_input\n");
        fclose(fp);
        return;
    }
   int count = fread(source, sizeof(char), file_size, fp);
   if (count < file_size) {
       perror("fp fread in char* user_file_input");
       return;
   }
    run(source);
    fclose(fp);
    free(source);
}


int main(int argc, char* argv[]) {
    if (argc == 1) {
        user_stdin_input();
    }
    else if (argc == 2) {
        user_file_input(argv[1]);
    }
    else {
        printf("您输入有误\n");
        return -1;
    }
    return 0;
}
